<?php


namespace App\Http\Controllers\Api;
use App\Enums\Common;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteAttach;
use App\Jobs\DeleteStar;
use App\Models\Category;
use App\Models\HoneyBalance;
use App\Models\Star;
use App\Models\User;
use App\Models\Work;
use App\Services\HoneyBalanceService;
use App\Services\SafeCheckService;
use Dingo\Api\Http\Request;

class WorkController extends BaseController
{
    public $model = Work::class;


    public function index(Request $request) {
        $this->validate($request, [
            'type' => 'filled|in:somebody,focus,star,all',
        ]);
        $input = $request->input();
        $input['type'] = $input['type'] ?? 'all';
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $parent_category_id = $request->input('parent_category_id');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        $user_id = $this->getUserId();

        $fields = '*';
        $list = Work::select($fields)->title($title)
            ->category($category_id)
            ->userStar($user_id)
            ->parentCategory($parent_category_id)
            ->with('category')
            ->withCertain('user', ['nickname', 'avatar_url', 'is_admin']);

        if ($input['type'] == 'focus') {
            $user = $this->getUser();
            $target_user_ids = [];
            if ($user) {
                $target_user_ids = $user->focus()->pluck('target_user_id')->all();
                array_push($target_user_ids, $user->id);
            }
            $list = $list->where('audit_status', Common::SUCCESS)->whereIn('user_id', $target_user_ids);
        }  else if($input['type'] == 'somebody') {
            $this->validate($request, [
                'target_user_id' => 'required',
            ]);
            $target_user_ids = [$input['target_user_id']];
            if ($input['target_user_id'] != $this->getUserId()) {
                $list = $list->where('audit_status', Common::SUCCESS);
            }
            $list = $list->whereIn('user_id', $target_user_ids);
        }  else if($input['type'] == 'star') {
            $user = $this->getUser();
            $target_entity_ids = $user->star()->where('type', 1)->pluck('entity_id')->all();
            $list = $list->where('audit_status', Common::SUCCESS)->whereIn('id', $target_entity_ids);
        } else {
            $list = $list->where('audit_status', Common::SUCCESS);
        }

        $list = $list->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }

    public function info(Request $request) {
        $id = \request("id");
        if (!$id) {
            return $this->failed("参数ID不存在");
        }
        $user = $this->user();
        $user_id = $user->id ?? 0;
        $work = Work::userStar($user_id)
            ->userFocus($user_id)
            ->withCertain('category', ['title'])
            ->withCertain('parent_category', ['title'])
            ->withCertain('user', ['nickname', 'avatar_url', 'is_admin'])
            ->find($id);

        $work->honey_num = $user->honey_balance ?? 0; //字段前端错误了 做兼容
        return $this->success($work);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $input = $request->input();
        $user = $this->getUser();
        $input['user_id'] = $this->getUserId();
        $id = \request("id");
        $category = Category::find($input['category_id']);
        if (SafeCheckService::handle($input['title']))
            return $this->failed('标题包含敏感词');

        if (SafeCheckService::handle($input['desc']))
            return $this->failed('内容包含敏感词');

        if (!$category)
            return $this->failed('分类id不存在');
        $input['parent_category_id'] = $category->parent_id;
        if ($id) {
            $model = Work::find($id);
            if (!$model) {
                return $this->failed("id对应数据不存在");
            }
            $input['audit_status'] = 0;
            $model->update($input);
        } else {
            $info = Work::create($input);
            $id = $info->id;
            $user->increment('work_count', 1);
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        foreach ($arr_id as $id) {
            $model = $this->model::find($id);
            if ($model) {

                if ($model->audit_status == 1)
                    HoneyBalanceService::store($model->user_id, -HoneyBalance::POINT_WORK, HoneyBalance::TYPE_WORK, $model->id, true);

                $attach = $model->image_file;
                $user_id = $model->user_id;
                $user = User::find($user_id);
                if ($user->work_count)
                    $user->increment('work_count', -1);

                if ($model->delete()){
                    dispatch(new DeleteAttach($attach));
                    dispatch(new DeleteStar(Star::TYPE_Work, $id, $user_id));
                }
            }
        }
        return $this->success([]);
    }

}

